Ext.define(
	'BookmarkIt.controller.BookmarkController',
				{
					extend : 'Ext.app.Controller',
					requires:['BookmarkIt.store.gapiManager'],
					stores : [ 'BookmarkIt.store.localBookmarks', 'BookmarkIt.store.folderContainerStore' ],
					models : [ 'BookmarkIt.model.Bookmark' ],
					views : [ 'BookmarkIt.view.EditBookmarkDialog', 'BookmarkIt.view.EditFolderDialog','BookmarkIt.view.bookmarkView', 'BookmarkIt.view.headerPanel', 'BookmarkIt.view.folderView' ],
					config : {
						currentFolderId : 0
					},
					init : function() {
						window.controller = this;
						var bookmarkController = this;
						bookmarkController.setCurrentFolderId(0);
						bookmarkController.arr = [];
						this.searchMode = false;
						
						var store = this.getStore('BookmarkIt.store.localBookmarks');
						store.load();
						store.filter({
							filterFn : function(rec) {
								return parseInt(rec.get("folderId"),10) === controller.getCurrentFolderId();
							}
						});
					},

					updateBookmark : function(button) {
						var win = button.up('window'), form = win.down('form'), record = form
								.getRecord(), values = form.getValues();
						if (typeof record !== 'undefined') {
							record.set(values);
							record.save();
						} else {
							var r = Ext.ModelManager.create(values,
									'BookmarkIt.model.Bookmark');
							this.getStore('BookmarkIt.store.localBookmarks').insert(0, r);
							r.save();
						}
						this.getStore('BookmarkIt.store.localBookmarks').load();
						win.close();
					},

					editBookmark : function(btn) {
						var grid = Ext.getCmp('bookmarkView');
						var bookmarks = grid.getSelectionModel().getSelection();
						var record = bookmarks[0];
						var view;
						if (record.get('url') !== '') {
							view = Ext.widget('bookmarkedit');
						} else {
							view = Ext.widget('folderedit');
						}
						view.down('form').loadRecord(record);
					},

					onBookmarkAddClick : function(button, event) {
						var controller = this;
						var store = this.getStore('BookmarkIt.store.localBookmarks');
						var input = Ext.ComponentQuery.query('#addUrlInput')[0];
						var tempCurrentFolderId = this.getCurrentFolderId();
						
						var inputValue = input.getValue();
						var date = new Date();
						var icon='';
						var title;

						store.clearFilter();
						var id = store.max('id')+1;
						if(!id){
							id=1;
						}
						store.filter({filterFn : function(rec) {return parseInt(rec.get("folderId"),10) === controller.getCurrentFolderId();}});
						
						
						var httpregexp = new RegExp('^http:\/\/');
                            httpsregexp = new RegExp('^https:\/\/');
                            main = new RegExp('(http\:\/\/|https\:\/\/)?.[^\/]+');

                            var formattedInputValue = main.exec(inputValue)[0];

						if (httpregexp.test(inputValue) || httpsregexp.test(inputValue)) {
							icon = formattedInputValue+'/favicon.ico';
						} else {	
							icon = 'http://' + formattedInputValue + '/favicon.ico';
							inputValue = 'http://' + inputValue;
						}

						var values = {};
						var titleUrl = "http://ajax.googleapis.com/ajax/services/search/web?q="
								+ inputValue + "&v=1.0&callback=?";
						
						function saveBookmark(title,imageObject) {
							values = {
								id : id,
								title : title,
								url : inputValue,
								icon : imageObject ? imageObject.unescapedUrl : icon,
								folderId : controller.getCurrentFolderId(),
								date : date
							};		
							var r = Ext.ModelManager.create(values,'BookmarkIt.model.Bookmark');
							
							if(imageObject){
								if(+imageObject.width > +imageObject.height){
									r.set('height',+imageObject.height/(+imageObject.width/118));	
									r.set('width',108);
								}else{
									r.set('width',+imageObject.width/(+imageObject.height/118));	
									r.set('height',108);
								}
							}
							
							store.add(r);
							r.save();
							input.setValue('');
						}
						
						
						function getIcon(title){
							$.ajax({
								url : 'http://ajax.googleapis.com/ajax/services/search/images?q='+formattedInputValue+'%20logo&v=1.0&callback=?',
								type : "GET",
								cache : false,
								dataType : "json",
								crossDomain : true,
								async : true,
								success : function(data) {
										saveBookmark(title,data.responseData.results[0]);
										store.load();
								},
							});
						}
						
						$.ajax({
								url : titleUrl,
								type : "GET",
								cache : false,
								dataType : "json",
								crossDomain : true,
								async : true,
								success : function(data) {
									try {
										title = data.responseData.results[0].titleNoFormatting;
										getIcon(title);
									} catch (e) {
										Ext.MessageBox.prompt('Bookmark Title','Please, enter the bookmark title',
													function(btn,text) {
														getIcon(text);
													});
										}
									},
								error : function() {
									Ext.MessageBox.prompt('Bookmark Title','Please, enter the bookmark title',
													function(btn, text) {
														getIcon(text);
													});
									}
								});
							
	
						
					},

					onBookmarkDelClick : function() {
						var store = this.getStore('BookmarkIt.store.localBookmarks');
						
						function recursDel(folderId) {
							var i;	
							for (i = 0; i < store.snapshot.items.length; i++) {
								var record = store.snapshot.items[i];
								if (record.get('folderId') === folderId) {
									if (record.get('url') !== '') {
											store.remove(record);
									} else {
										recursDel(record.get('id'));
										store.remove(record);
									}
								}
							}
						}
						
						var i;
						var grid = Ext.getCmp('bookmarkView');
						var bookmarksToBeDestroyed = grid.getSelectionModel()
								.getSelection();
						for (i = 0; i < bookmarksToBeDestroyed.length; ++i) {
							if (bookmarksToBeDestroyed[i].get('url') !== '') {
									store.remove(bookmarksToBeDestroyed[i]);
							} else {
								var id = bookmarksToBeDestroyed[i].get('id');
								recursDel(id);
								store.remove(bookmarksToBeDestroyed[i]);
							}
						}
						store.sync();			
					},

					onFolderAddClick : function() {
						var controller = this;
						var store = this.getStore('BookmarkIt.store.localBookmarks');
						store.clearFilter();
						var id = store.max('id')+1;
						if(!id){
							id=1;
						}
						
						store.filter({filterFn : function(rec) {return parseInt(rec.get("folderId"),10) === controller.getCurrentFolderId();}});
						
						if (this.getStore('BookmarkIt.store.folderContainerStore').count() < 6) {
							values = {
								id : id,
								title : 'New Folder',
								url : '',
								folderId : controller.getCurrentFolderId()
							}
							var folderModel = Ext.ModelManager.create(values,
									'BookmarkIt.model.Bookmark');							
							
							store.add(folderModel);
							folderModel.save();
						} else {
							Ext.Msg.alert('Error','Sorry, you can\'t go deeper');
						}
					},

					folderExplore : function(grid, rec, item, index, event) {
						var controller = this;
						this.setCurrentFolderId(rec.get('id'));
						grid.store.clearFilter();
						grid.store.filter({
							filterFn : function(rec) {
								return parseInt(rec.get("folderId"),10) === controller.getCurrentFolderId();
							}
						});
						this.getStore('BookmarkIt.store.folderContainerStore').add(
								grid.store.getById(controller.getCurrentFolderId()));
					},

					goToFolder : function(obj) {

						var folderContainerStore = this.getStore('BookmarkIt.store.folderContainerStore');
						var record = folderContainerStore.getById(obj.id);
						var index = folderContainerStore.indexOf(record);
						var temp = [];
						folderContainerStore.each(function(rec) {
							if (folderContainerStore.indexOf(rec) > index) {
								temp.push(rec);
							}
						});
						folderContainerStore.remove(temp);
						if (record) {
							this.setCurrentFolderId(record.get('id'));
						} else{
							this.setCurrentFolderId(0);							
						}
					},

					upFolder : function() {
						if (this.getCurrentFolderId() !== 0) {
							var outerFolderId;
							var grid = Ext.getCmp('bookmarkView');
							var innerFolder = grid.store.getById(this
									.getCurrentFolderId());
							if (innerFolder !== null) {
								outerFolderId = innerFolder.get('folderId');
							} else{
								outerFolderId = 0;								
							}
							grid.store.clearFilter();
							grid.store.filter({
										filterFn : function(rec) {
											return parseInt(rec.get("folderId"),10) === outerFolderId;
										}
									});
							this.setCurrentFolderId(outerFolderId);
							var store = this.getStore('BookmarkIt.store.folderContainerStore');
							store.remove(store.last());
						}
					}

				});